<script lang="ts" setup>
import type { UploadProps } from 'element-plus'
import { useSystemStore } from '@/stores/system'
import { useTemporaryStore } from '@/stores/temporary'

const systemStore = useSystemStore()
const temporaryStore = useTemporaryStore()
const uploadRef = ref()

const { multiple } = defineProps({
  multiple: {
    type: Number,
    default: 1
  }
})

const handleChange: UploadProps['onChange'] = (uploadFile, uploadFiles) => {
  temporaryStore.upload.formData = new FormData()
  for (let i = temporaryStore.upload.urls.length; i < uploadFiles.length; i++) {
    temporaryStore.upload.formData.append('files', uploadFiles[i].raw!)
  }
}

const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  temporaryStore.upload.urls = uploadFiles
}

// 图片预览
const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  systemStore.imgPreview.imgUrl = uploadFile.url!
}

onMounted(() => {
  temporaryStore.upload.uploadRef = uploadRef.value
})
</script>

<template>
  <el-upload
    ref="uploadRef"
    :auto-upload="false"
    :file-list="temporaryStore.upload.urls"
    :limit="multiple"
    :on-change="handleChange"
    :on-preview="handlePictureCardPreview"
    :on-remove="handleRemove"
    list-type="picture-card"
    multiple
  >
    <SvgIcon name="add" svg-class="!size-5" />
  </el-upload>
</template>

<style lang="scss">
.el-upload-list .el-upload,
.el-upload-list__item,
.el-upload__input,
.el-upload-list__item-actions {
  width: 100px !important;
  height: 100px !important;
}

.el-overlay {
  position: fixed !important;
}
</style>
